package com.xstudio.pvzreborn.utils.registry;

import com.xstudio.pvzreborn.PVZReborn;
import com.xstudio.pvzreborn.utils.registry.holder.Holder;
import org.jetbrains.annotations.Nullable;

import java.util.Map;

public abstract class RegistrationHelper<P, T> {

    /**
     * 贴图文件夹名称
     */
    protected final String groupName;
    /**
     * 待注册元素的名称 (key) 和部分信息 (value)
     */
    protected final Map<String, Holder<P, T>> registry;
    /**
     * 默认的注册行为
     */
    protected final RegistrationAction<P, T> defaultRegistryAction;
    /**
     * 上一个注册的元素的名称
     */
    protected String previousName;

    public RegistrationHelper(String groupName, Map<String, Holder<P, T>> registry, @Nullable RegistrationAction<P, T> defaultRegistryAction) {
        this.registry = registry;
        this.groupName = groupName;
        this.defaultRegistryAction = defaultRegistryAction;
    }

    /**
     * @param properties 新的属性
     * @return this
     */
    public RegistrationHelper<P, T> properties(P properties) {
        if (previousName != null && registry.containsKey(previousName)) {
            registry.get(previousName).setProperties(properties);
        } else {
            PVZReborn.LOGGER.error(new IllegalStateException("Try to add properties to a non-existent element"));
        }
        return this;
    }

    /**
     * @param name 待注册元素的名称, 并使用默认注册行为
     */
    public RegistrationHelper<P, T> addElement(String name) {
        if (defaultRegistryAction == null) {
            PVZReborn.LOGGER.error(new UnsupportedOperationException("defaultRegistryAction is null"));
        } else return addElement(name, defaultRegistryAction);
        return this;
    }

    /**
     * @param name     待元素物品的名称
     * @param supplier 注册行为, 决定该物品如何注册
     */
    public abstract RegistrationHelper<P, T> addElement(String name, RegistrationAction<P, ? extends T> supplier);

    public abstract void register();

}
